﻿using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using Hotel.UI.Helpers;
using System.IO;
using Microsoft.Win32;
using System.Windows.Interop;
using Ay.Framework.WPF.Controls;
using Microsoft.WindowsAPICodePack.Dialogs;
using Hotel.UI.Common;
using Hotel.UI.Utils;
namespace Hotel.UI.Controls
{
    public partial class ImageEditor : UserControl
    {
        public Visibility EditBarVisible
        {
            get { return (Visibility)GetValue(EditBarVisibleProperty); }
            set { SetValue(EditBarVisibleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for EditBarVisible.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EditBarVisibleProperty =
            DependencyProperty.Register("EditBarVisible", typeof(Visibility), typeof(ImageEditor), new PropertyMetadata(Visibility.Visible));
        public System.Windows.Forms.Screen GetCurrentScreen(Window window)
        {
            return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
        }


        public ImageEditor()
        {
            InitializeComponent();

            var dpi = VisualTreeHelper.GetDpi(this);
            if (ThemeManager.AYBANQUAN)
            {
                Loaded += AyImageList_Loaded;
                Unloaded += AyImageList_Unloaded;
                AyThread.Instance.InitDispatcher(this.Dispatcher);
            }
            if (WpfTreeHelper.IsInDesignMode)
            {
                this.Background = new SolidColorBrush(Colors.Gray);
                this.Content = "图片列表区域";
                this.VerticalContentAlignment = VerticalAlignment.Center;
                this.HorizontalContentAlignment = HorizontalAlignment.Center;
                this.FontSize = 32;
            }

            this.Loaded += (ss, ee) =>
            {
                Window target = Window.GetWindow(this);
                var win = Hotel.UI.Helpers.Utils.FindVisualParent<Window>(this);

                var dpi2 = VisualTreeHelper.GetDpi(this);

            };

            //ListBoxStart.PreviewMouseDown += ListBoxStart_PreviewMouseDown;
            ListBoxStart.PreviewMouseMove += ListBoxStart_OnPreviewMouseMove;
            ListBoxStart.QueryContinueDrag += ListBoxStart_QueryContinueDrag;
            ListBoxStart.GiveFeedback += ListBoxStart_GiveFeedback;

            ListBoxEnd.GiveFeedback += ListBoxEnd_GiveFeedback;
        }

        private void ListBoxEnd_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effects == DragDropEffects.Copy)
                Mouse.SetCursor(Cursors.Cross); //拖动复制显示红十字
            else
                Mouse.SetCursor(Cursors.Hand);
            //Mouse.SetCursor(Cursors.Arrow);//修改鼠标样式
            e.UseDefaultCursors = false;
            e.Handled = true;
        }

        private void ListBoxStart_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effects == DragDropEffects.Copy)
                Mouse.SetCursor(Cursors.Arrow); //拖动复制显示红十字
            else
                Mouse.SetCursor(Cursors.Hand);
            //Mouse.SetCursor(Cursors.Arrow);//修改鼠标样式
            e.UseDefaultCursors = false;
            e.Handled = true;
        }
        #region  ListBoxStart 向 ListBoxEnd 复制移动 ListBoxItem
        //private void ListBoxStart_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        //{
        //    Debug.WriteLine("点我了");
        //    //var listBoxItem = VisualUpwardSearch<ListBoxItem>(e.OriginalSource as DependencyObject) as ListBoxItem;
        //    //if (listBoxItem == null) return;
        //    //AyImageListItemFromByte image = (AyImageListItemFromByte)listBoxItem.DataContext;
        //    //DragDrop.DoDragDrop(listBoxItem, image, DragDropEffects.Copy);
        //}
        public DependencyObject VisualUpwardSearch<T>(DependencyObject source)
        {

            while (source != null && source.GetType() != typeof(T))
                source = VisualTreeHelper.GetParent(source);

            return source;
        }

        private void ListBoxStart_OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.LeftButton != MouseButtonState.Pressed)
                return;

            Point pos = e.GetPosition(ListBoxStart);
            HitTestResult result = VisualTreeHelper.HitTest(ListBoxStart, pos);
            if (result == null)
                return;
            //result.VisualHit 可能是 滑片 Thumb/border.
            ListBoxItem listBoxItem = Hotel.UI.Helpers.Utils.FindVisualParent<ListBoxItem>(result.VisualHit); // Find your actual visual you want to drag
            if (listBoxItem == null || listBoxItem.Content != ListBoxStart.SelectedItem || !(ListBoxStart.SelectedItem is AyImageListItemFromByte))
                return;
            Debug.WriteLine("点击滚动啦1");
            var listBoxItem2 = VisualUpwardSearch<ListBoxItem>(e.OriginalSource as DependencyObject) as ListBoxItem;
            if (listBoxItem2 == null)
            {
                Debug.WriteLine("点击滚动啦2");
                return;
            }

            DragDropAdorner adorner = new DragDropAdorner(listBoxItem);
            mAdornerLayer = AdornerLayer.GetAdornerLayer(mTopLevelGrid); // Window class do not have AdornerLayer
            mAdornerLayer.Add(adorner);

            AyImageListItemFromByte dataItem = listBoxItem.Content as AyImageListItemFromByte;
            //DataObject dataObject = new DataObject(dataItem.Clone());
            DataObject dataObject = new DataObject(dataItem);
            System.Windows.DragDrop.DoDragDrop(ListBoxStart, dataObject, DragDropEffects.Copy);

            mStartHoverTime = DateTime.MinValue;
            mHoveredItem = null;
            mAdornerLayer?.Remove(adorner);
            mAdornerLayer = null;
        }
        private bool isDragging;
        private ListBoxItem item;
        private ListBoxItem dragItem;
        private object data;
        DateTime mStartHoverTime = DateTime.MinValue;
        TreeViewItem mHoveredItem = null;
        AdornerLayer mAdornerLayer = null;
        private void ListBoxStart_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
        {
            if (mAdornerLayer == null) return;
            mAdornerLayer.Update();
            UpdateTreeViewExpandingState();
        }
        private void UpdateTreeViewExpandingState()
        {
            Win32.POINT point = new Win32.POINT();
            if (Win32.GetCursorPos(ref point))
            {
                Point pos = new Point(point.X, point.Y);
                pos = ListBoxEnd.PointFromScreen(pos);
                HitTestResult result = VisualTreeHelper.HitTest(ListBoxEnd, pos);
                if (result != null)
                {
                    TreeViewItem selectedItem = Hotel.UI.Helpers.Utils.FindVisualParent<TreeViewItem>(result.VisualHit);
                    if (selectedItem != null)
                    {
                        if (mHoveredItem != selectedItem)
                        {
                            mHoveredItem = selectedItem;
                            mStartHoverTime = DateTime.Now;
                        }
                        else
                        {
                            if (mHoveredItem.Items.Count > 0 && !mHoveredItem.IsExpanded &&
                                DateTime.Now - mStartHoverTime > TimeSpan.FromSeconds(1))
                                mHoveredItem.IsExpanded = true;
                        }
                    }
                }
            }
        }

        private void ListBoxEnd_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;
            Point pos = e.GetPosition(ListBoxEnd);
            HitTestResult result = VisualTreeHelper.HitTest(ListBoxEnd, pos);
            if (result == null)
                return;

            //ListBoxItem selectedItem = Hotel.UI.Helpers.Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
            //if (selectedItem != null)
            //    selectedItem.IsSelected = true;
            AyImageListItemFromByte dataItem = e.Data.GetData(typeof(AyImageListItemFromByte)) as AyImageListItemFromByte;
            if (this.ItemsSourceB.Contains(dataItem)) return;

            e.Effects = DragDropEffects.Copy;
        }

        private void ListBoxEnd_Drop(object sender, DragEventArgs e)
        {
            Point pos = e.GetPosition(ListBoxEnd);
            HitTestResult result = VisualTreeHelper.HitTest(ListBoxEnd, pos);
            if (result == null)
                return;

            //TreeViewItem selectedItem = Utils.FindVisualParent<TreeViewItem>(result.VisualHit);
            //if (selectedItem == null)
            //    return;

            //DataItem parent = selectedItem.Header as DataItem;
            AyImageListItemFromByte dataItem = e.Data.GetData(typeof(AyImageListItemFromByte)) as AyImageListItemFromByte;
            //if (parent != null && dataItem != null)
            //    parent.Items.Add(dataItem);
            if (this.ItemsSourceB.Contains(dataItem)) return;
            ItemsSourceB.Add(dataItem);
            this.ListBoxEnd.ItemsSource = ItemsSourceB;
        }

        #endregion
        private void AyImageList_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyImageList_Loaded;
            win = Window.GetWindow(this);
            if (null != win)
            {
                win.Closing += W_Closing;
            }
            ScrollViewerExpand.SetMouseWheel_H(ListBoxStart);


            imageTool = new MouseZoomMoveTool(masterImage);


        }
        MouseZoomMoveTool imageTool;
        private void AyImageList_Unloaded(object sender, RoutedEventArgs e)
        {
            if (null != win)
            {
                win.Closing -= W_Closing;
            }
            ClearResource();
        }

        public System.Collections.IEnumerable ItemsSource
        {
            get { return (System.Collections.IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }
        public ObservableCollection<AyImageListItemFromByte> ItemsSourceB
        {
            get; set;
        } = new ObservableCollection<AyImageListItemFromByte>();
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(System.Collections.IEnumerable), typeof(ImageEditor), new PropertyMetadata(null));

        //private static void OnItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        //{
        //    AyImageList box = d as AyImageList;

        //    if (box == null)
        //    {
        //        return;
        //    }



        //}

        private void W_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ClearResource();
        }
        bool clearResource = true;
        private void ClearResource()
        {
            clearResource = false;
            //删除临时图片
            var _list = ItemsSource as ObservableCollection<AyImageListItemFromByte>;
            if (_list != null)
            {
                foreach (var item in _list)
                {
                    //if (item.FileNameTemp.IsNotNull())
                    //{
                    //    System.IO.File.Delete(item.FileNameTemp);
                    //}
                }
            }
            _list?.Clear();
            win = null;
            var myProcesses = Process.GetProcessesByName(ProcessName);
            foreach (Process myprocess in myProcesses)
            {
                myprocess.Kill();
            }
            AyThread.Instance.InitDispatcher(null);
            AyCommon.MemoryGC();
        }





        public object SelectedItem
        {
            get { return (object)GetValue(SelectedItemProperty); }
            set { SetValue(SelectedItemProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(object), typeof(ImageEditor), new PropertyMetadata(null));

        //private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        //{
        //    AyImageList box = d as AyImageList;

        //    if (box == null)
        //    {
        //        return;
        //    }
        //    //var _1 = e.NewValue as AyImageListItemFromByte;

        //    box.ListBox_SelectionChanged();
        //}






        //public void UpdateImageSource(AyImageListItemFromByte uri)
        //{
        //    AyThread.Instance.RunNew<Source>(() =>
        //    {
        //        //var s = new BitmapImage();
        //        //s.BeginInit();
        //        //s.CacheOption = BitmapCacheOption.OnLoad;
        //        ////打开文件流
        //        //using (var stream = System.IO.File.OpenRead(uri.ImageUri))
        //        //{
        //        //    s.StreamSource = stream;
        //        //    s.EndInit();
        //        //    s.Freeze();
        //        //}
        //        var s = ImageResources.ByteArrayToBitmapImage(uri.ImageByte, null, null);
        //        s.Freeze();
        //        return s;

        //    }, (source) =>
        //    {
        //        AyThread.Instance.RunUI(() =>
        //        {
        //            bigImage.Source = source;
        //            busying.IsBusy = false;
        //        });

        //    });
        //}


        #region 主图操作 移动/缩放

        private bool m_IsMouseLeftButtonDown;
        private void MasterImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Grid rectangle = sender as Grid;
            if (rectangle == null)
                return;

            rectangle.ReleaseMouseCapture();
            m_IsMouseLeftButtonDown = false;
        }

        /// <summary>
        /// 鼠标的位置
        /// </summary>
        private Point m_PreviousMousePoint;

        /// <summary>
        /// 鼠标左键按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Grid rectangle = sender as Grid;
            if (rectangle == null)
                return;

            rectangle.CaptureMouse();//捕获鼠标
            m_IsMouseLeftButtonDown = true;
            m_PreviousMousePoint = e.GetPosition(rectangle);
        }

        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseMove(object sender, MouseEventArgs e)
        {
            Grid rectangle = sender as Grid;
            if (rectangle == null)
                return;

            if (m_IsMouseLeftButtonDown)
                DoImageMove(rectangle, e);
        }

        /// <summary>
        /// 开始移动
        /// </summary>
        /// <param name="rectangle"></param>
        /// <param name="e"></param>
        private void DoImageMove(Grid rectangle, MouseEventArgs e)
        {
            //Debug.Assert(e.LeftButton == MouseButtonState.Pressed);
            if (e.LeftButton != MouseButtonState.Pressed)
                return;

            TransformGroup group = masterImage.RenderTransform as TransformGroup;
            Debug.Assert(group != null);
            TranslateTransform transform = group.Children[1] as TranslateTransform;
            Point position = e.GetPosition(rectangle);
            transform.X += position.X - m_PreviousMousePoint.X;
            transform.Y += position.Y - m_PreviousMousePoint.Y;
            m_PreviousMousePoint = position;
            Debug.WriteLine($" transform.X :{transform.X},transform.Y:{transform.Y}");
        }
        /// <summary>
        /// 滚轮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseWheel(object sender, MouseWheelEventArgs e)
        {

            Point point = e.GetPosition(masterImage);
            double scale = e.Delta * 0.0015;
            ZoomImage(point, scale);

        }
        private void ZoomImage(Point point, double scale)
        {
            TransformGroup group = masterImage.RenderTransform as TransformGroup;
            ScaleTransform transform = group.Children[0] as ScaleTransform;
            Debug.WriteLine($"--------transform.CenterX:{transform.CenterX},transform.CenterY:{transform.CenterY},transform.ScaleX:{transform.ScaleX},transform.ScaleY:{transform.ScaleY}");
            //缩放图片后，把缩放后图片上的坐标转换为在原始图片的坐标，从而使图片正常缩放。
            Point pointToContent = group.Inverse.Transform(point);

            transform.CenterX = 0; transform.CenterY = 0;
            if (transform.ScaleX + scale < 0.5)
            {
                return;
            }
            transform.ScaleX += scale;
            transform.ScaleY += scale;
            TranslateTransform transform1 = group.Children[1] as TranslateTransform;
            transform1.X = -1 * ((pointToContent.X * transform.ScaleX) - point.X);
            transform1.Y = -1 * ((pointToContent.Y * transform.ScaleY) - point.Y);

        }
        //private void MasterImage_MouseWheel(object sender, MouseWheelEventArgs e)
        //{
        //    var d = e.Delta / 1000.0;
        //    if (scale.ScaleX < 0.2 && scale.ScaleY < 0.2 && e.Delta < 0)
        //    {
        //        return;
        //    }
        //    scale.ScaleX += d;
        //    scale.ScaleY += d;
        //    e.Handled = true;
        //}

        private void ScaleTransformStoryboard(double scaleX, double scaleY, double centerX, double centerY)
        {

            try
            {
                TransformGroup group = masterImage.RenderTransform as TransformGroup;
                var scaleTransform = group.Children[0] as ScaleTransform;
                //this.RegisterName("AnimatedScaleTransform", scaleTransform);
                scaleTransform.CenterX = centerX;
                scaleTransform.CenterY = centerY;
                scaleTransform.ScaleY = scaleY;
                scaleTransform.ScaleX = scaleX;

                //var storyboard = new Storyboard();
                ////DoubleAnimation doubleAnimationX = new DoubleAnimation(0, 360, new Duration(TimeSpan.FromMilliseconds(1000)));
                //var doubleAnimationX = new DoubleAnimation();
                ////doubleAnimationX.From = 500;
                //doubleAnimationX.To = scaleX;
                //doubleAnimationX.Duration = new Duration(TimeSpan.FromSeconds(1));

                //Storyboard.SetTargetName(doubleAnimationX, "AnimatedScaleTransform");
                //Storyboard.SetTargetProperty(doubleAnimationX, new PropertyPath(ScaleTransform.ScaleXProperty));
                //storyboard.Children.Add(doubleAnimationX);

                //var doubleAnimationY = new DoubleAnimation();
                ////doubleAnimationX.From = 500;
                //doubleAnimationY.To = scaleY;
                //doubleAnimationY.Duration = new Duration(TimeSpan.FromSeconds(1));
                //Storyboard.SetTargetName(doubleAnimationY, "AnimatedScaleTransform");
                //Storyboard.SetTargetProperty(doubleAnimationY, new PropertyPath(ScaleTransform.ScaleYProperty));
                //storyboard.Children.Add(doubleAnimationY);

                //storyboard.Begin(this);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        private void TranslateTransformStoryboard(double x, double y)
        {

            try
            {
                //TransformGroup group = masterImage.RenderTransform as TransformGroup;
                //var translateTransform = group.Children[1] as TranslateTransform;
                //translateTransform.X = x;
                //translateTransform.Y = y;
                //var storyboard = new Storyboard();
                //this.RegisterName("AnimatedTranslateTransform", translateTransform);

                ////DoubleAnimation doubleAnimationX = new DoubleAnimation(0, 360, new Duration(TimeSpan.FromMilliseconds(1000)));
                //var doubleAnimationX = new DoubleAnimation();
                ////doubleAnimationX.From = 500;
                //doubleAnimationX.To = x;
                //doubleAnimationX.Duration = new Duration(TimeSpan.FromSeconds(1));

                //Storyboard.SetTargetName(doubleAnimationX, "AnimatedTranslateTransform");
                //Storyboard.SetTargetProperty(doubleAnimationX, new PropertyPath(TranslateTransform.XProperty));
                //storyboard.Children.Add(doubleAnimationX);

                //var doubleAnimationY = new DoubleAnimation();
                ////doubleAnimationX.From = 500;
                //doubleAnimationY.To = y;
                //doubleAnimationY.Duration = new Duration(TimeSpan.FromSeconds(1));
                //Storyboard.SetTargetName(doubleAnimationY, "AnimatedTranslateTransform");
                //Storyboard.SetTargetProperty(doubleAnimationY, new PropertyPath(TranslateTransform.YProperty));
                //storyboard.Children.Add(doubleAnimationY);

                //storyboard.Begin(this);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        //按窗口大小显示
        private void btnImageReset_Click(object sender, RoutedEventArgs e)
        {
            imageTool?.ReSet();
            ////Now since you got the image displayed in Image control. You can easily map the mouse position to the Pixel scale.  
            ////TransformGroup group = masterImage.RenderTransform as TransformGroup;
            ////Debug.Assert(group != null);
            ////ScaleTransform scaleTransform = group.Children[0] as ScaleTransform;
            ////TranslateTransform translateTransform = group.Children[1] as TranslateTransform;
            //ScaleTransformStoryboard(1, 1, 0, 0);
            ////scaleTransform.ScaleX = 1;
            ////scaleTransform.ScaleY = 1;
            ////translateTransform.X = 0;
            ////translateTransform.Y = 0;
            //TranslateTransformStoryboard(0, 0);
        }
        //原图显示
        private void btnImageOriginal_Click(object sender, RoutedEventArgs e)
        {
            imageTool?.ShowOriginalImage();
            //var AW = masterImage.ActualWidth;
            //var AH = masterImage.ActualHeight;

            //var OW = masterImage.Source.Width;
            //var OH = masterImage.Source.Height;
            //TranslateTransformStoryboard(0, 0);
            //ScaleTransformStoryboard(OW / AW, OH / AH, masterImage.ActualWidth / 2, masterImage.ActualHeight / 2);

        }
        #endregion

        public void SetImageCoordinate(double x, double y)
        {

            TransformGroup group = masterImage.RenderTransform as TransformGroup;
            Debug.Assert(group != null);
            ScaleTransform scaleTransform = group.Children[0] as ScaleTransform;
            TranslateTransform translateTransform = group.Children[1] as TranslateTransform;

            var imageSource = masterImage.Source;
            BitmapImage bitmapImage = (BitmapImage)imageSource;
            //Now since you got the image displayed in Image control. You can easily map the mouse position to the Pixel scale.

            //var pixelMousePositionX = -(x) / bitmapImage.PixelWidth * scaleTransform.ScaleX * bigImage.ActualWidth;
            //var pixelMousePositionY = -(y) / bitmapImage.PixelHeight * scaleTransform.ScaleY * bigImage.ActualHeight;

            ////MessageBox.Show("X: " + pixelMousePositionX + "; Y: " + pixelMousePositionY);

            //var tt = (TranslateTransform)((TransformGroup)bigImage.RenderTransform).Children.First(tr => tr is TranslateTransform);
            //tt.X = pixelMousePositionX;
            //tt.Y = pixelMousePositionY;
        }

        //private void ImgThumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        //{
        //    double left = Grid.GetLeft(bigImage);
        //    double top = Grid.GetTop(bigImage);
        //    Grid.SetLeft(bigImage, (left + e.HorizontalChange));
        //    Grid.SetTop(bigImage, (top + e.VerticalChange));
        //}
        public event EventHandler<ImageEditedEventArgs> OnImageEdited;

        Window win = null;
        private void btnEditImage_Click(object sender, RoutedEventArgs e)
        {
            //var uri = ListBoxStart.SelectedItem as AyImageListItemFromByte;
            //if (uri == null) return;
            //string file = null;
            //if (uri.FileNameTemp.IsNullOrWhiteSpace())
            //{
            //    file = AyCommon.GetGuidNoSplit;
            //    uri.FileNameTemp = AyuiConfig.Get_AYUI_TempDirectory() + file + ".jpg";
            //}
            //else
            //{
            //    file = System.IO.Path.GetFileNameWithoutExtension(uri.FileNameTemp);
            //}
            ////存储到临时文件夹
            //ImageResources.SaveLocal(uri.FileNameTemp, masterImage.Source as BitmapSource);
            ////启动监视,一有变动就更新
            //Process[] myProcesses = Process.GetProcessesByName(ProcessName);//需要监控的程序名，该方法带出该程序所有用到的进程
            //string processname = ("{0}").StringFormat(file);
            //var _s = myProcesses.FirstOrDefault<Process>(x => x.MainWindowTitle.Equals(processname));
            //if (_s.IsNotNull())
            //{
            //    HandleRunningInstance(_s);
            //}
            //else
            //{
            //    //反馈编辑器
            //    var p = AyFuncSystem.StartProcess(DefaultEditImageExePath, new string[] { uri.FileNameTemp });

            //    //System.Threading.Thread.Sleep(3000);//等待程序打开,打开后找到进程
            //    //添加任务，每个任务最多执行10秒
            //    new AyTimeEx(1000, (timer) =>
            //    {
            //        Process[] myProcesses2 = Process.GetProcessesByName(ProcessName);
            //        foreach (Process myprocess in myProcesses2)
            //        {
            //            if (myprocess.MainWindowTitle.Contains(processname))
            //            {
            //                myprocess.EnableRaisingEvents = true;//设置进程终止时触发的时间
            //                myprocess.Exited += (send, ee) =>
            //                {
            //                    if (clearResource)
            //                    {

            //                        uri.ImageByte = ImageResources.GetImageByteByUri(uri.FileNameTemp);
            //                        if (OnImageEdited != null)
            //                            OnImageEdited(this, new ImageEditedEventArgs { ImageData = uri.ImageByte, FileName = uri.FileName });

            //                    }
            //                };
            //                timer.Stop();
            //            }
            //        }
            //    }, 30).Start();


            //}
        }


        private static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 1);  //调用api函数，正常显示窗口
            SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
        }

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);


        //public string ProcessNameHouZhui
        //{
        //    get { return (string)GetValue(ProcessNameHouZhuiProperty); }
        //    set { SetValue(ProcessNameHouZhuiProperty, value); }
        //}

        //// Using a DependencyProperty as the backing store for ProcessNameHouZhui.  This enables animation, styling, binding, etc...
        //public static readonly DependencyProperty ProcessNameHouZhuiProperty =
        //    DependencyProperty.Register("ProcessNameHouZhui", typeof(string), typeof(AyImageList), new PropertyMetadata(" - 画图"));





        public string ProcessName
        {
            get { return (string)GetValue(ProcessNameProperty); }
            set { SetValue(ProcessNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ProcessName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ProcessNameProperty =
            DependencyProperty.Register("ProcessName", typeof(string), typeof(ImageEditor), new PropertyMetadata("mspaint"));



        public string DefaultEditImageExePath
        {
            get { return (string)GetValue(DefaultEditImageExePathProperty); }
            set { SetValue(DefaultEditImageExePathProperty, value); }
        }

        public static readonly DependencyProperty DefaultEditImageExePathProperty =
            DependencyProperty.Register("DefaultEditImageExePath", typeof(string), typeof(ImageEditor), new PropertyMetadata("mspaint.exe"));

        //private void btntest1_Click(object sender, RoutedEventArgs e)
        //{
        //    //AyMessageBox.Show(bigImage.ActualWidth.ToString() + "," + bigImage.ActualHeight.ToString());
        //}

        //private void navi_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    ListBox_SelectionChanged();
        //}

        //private void Image_Loaded(object sender, RoutedEventArgs e)
        //{
        //    Image i = sender as Image;
        //    if (i.IsNotNull())
        //    { 
        //        var descriptor = DependencyPropertyDescriptor.FromProperty(Image.SourceProperty, typeof(Image));
        //        descriptor.AddValueChanged(i, (o, args) =>
        //        {
        //            if (navi.SelectedItem == i.Tag)
        //            {
        //                UpdateImageSource(navi.SelectedItem as AyImageListItemFromByte);
        //            }
        //        });
        //    }
        //}
        //private void Image_SourceUpdated(object sender, DataTransferEventArgs e)
        //{
        //    Image i = sender as Image;
        //    if (i.IsNotNull())
        //    {
        //        if (navi.SelectedItem == i.Tag)
        //        {
        //            UpdateImageSource(navi.SelectedItem as AyImageListItemFromByte);
        //        }
        //    }
        //}

        private void btnOpenImage_Click(object sender, RoutedEventArgs e)
        {
            ObservableCollection<AyImageListItemFromByte> lists = new ObservableCollection<AyImageListItemFromByte>();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter =
    "All Image Files|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff|" +
    "Windows Bitmap(*.bmp)|*.bmp|" +
    "Windows Icon(*.ico)|*.ico|" +
    "Graphics Interchange Format (*.gif)|(*.gif)|" +
    "JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg|" +
    "Portable Network Graphics (*.png)|*.png|" +
    "Tag Image File Format (*.tif)|*.tif;*.tiff";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog.Title = "选择图片";
            openFileDialog.Multiselect = true; // 允许多选
            if (openFileDialog.ShowDialog() == true)
            {
                var dpi = VisualTreeHelper.GetDpi(this);
                //txtFilePath.Text = openFileDialog.FileName;
                foreach (var fileName in openFileDialog.FileNames)
                {

                    AyImageListItemFromByte b1 = new AyImageListItemFromByte();
                    //b1.ImageByte = ImageResources.GetImageByteByUri(file.FullName);
                    //b1.ImgSource = ImageResources.GetImageSource(dpi, fileName);
                    b1.FileName = AyCommon.GetGuidNoSplit;

                    lists.Add(b1);
                }
                ItemsSource = lists;
            }
        }

        private void btnOpenFolder_Click(object sender, RoutedEventArgs e)
        {
            ObservableCollection<AyImageListItemFromByte> lists = new ObservableCollection<AyImageListItemFromByte>();
            //var dialog = new System.Windows.Forms.FolderBrowserDialog(); 
            //var result = dialog.ShowDialog();
            //if (result == System.Windows.Forms.DialogResult.OK)

            CommonOpenFileDialog dialog = new CommonOpenFileDialog("请选择图片文件夹");
            dialog.IsFolderPicker = true; //选择文件还是文件夹（true:选择文件夹，false:选择文件）
            dialog.Multiselect = true;

            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                var dpi = VisualTreeHelper.GetDpi(this);
                // var folderPath = dialog.FileName;// "D:\\素材\\国风美女出游";
                foreach (var folderPath in dialog.FileNames)
                {
                    DirectoryInfo di = new DirectoryInfo(folderPath);
                    //FileInfo[] files = folder.GetFiles("*.*", SearchOption.AllDirectories);
                    FileInfo[] files = di.GetFiles("*.bmp")
                                            .Union(di.GetFiles("*.jpg"))
                                            .Union(di.GetFiles("*.png"))
                                            .Union(di.GetFiles("*.jpeg"))
                                            .Union(di.GetFiles("*.tiff"))
                                            .Union(di.GetFiles("*.webp"))
                                            .ToArray();
                    foreach (FileInfo file in files)
                    {
                        AyImageListItemFromByte b1 = new AyImageListItemFromByte();
                        //b1.ImageByte = ImageResources.GetImageByteByUri(file.FullName);
                        //b1.ImgSource = ImageResources.GetImageSource(dpi, file.FullName);
                        b1.FileName = AyCommon.GetGuidNoSplit;

                        lists.Add(b1);
                    }
                }
                ItemsSource = lists;
            }
        }

        private void MenuItemAddTo_Click(object sender, RoutedEventArgs e)
        {
            AyImageListItemFromByte dataItem = this.ListBoxStart.SelectedItem as AyImageListItemFromByte;
            if (dataItem != null)
            {
                if (this.ItemsSourceB == null)
                    this.ItemsSourceB = new ObservableCollection<AyImageListItemFromByte>();
                if (this.ItemsSourceB.Contains(dataItem))
                    return;
                ItemsSourceB.Add(dataItem);
                //this.ListBoxEnd.ItemsSource = ItemsSourceB;
            }
        }

        private void MenuItemViewTo_Click(object sender, RoutedEventArgs e)
        {
            AyImageListItemFromByte dataItem = this.ListBoxEnd.SelectedItem as AyImageListItemFromByte;
            if (dataItem != null)
            {
                this.SelectedItem = dataItem;
            }
        }

        private void MenuItemRemoveTo_Click(object sender, RoutedEventArgs e)
        {
            AyImageListItemFromByte dataItem = this.ListBoxEnd.SelectedItem as AyImageListItemFromByte;
            if (dataItem != null)
            {
                this.ItemsSourceB.Remove(dataItem);
            }
        }
    }
}
